package za.co.green;

import java.io.*;
import java.net.*;

public class UDPServerThread extends Thread {

	
    protected MulticastSocket socket = null;
    
    protected final int FIVE_SECONDS = 50000;
    
    private String bindAddr = "";
    
    private int udpPort = 0;
    
    private String brdCstMsg = "";

    public UDPServerThread(String bindAddr, int udpPort, String brdCstMsg) throws IOException {
	    	this("UDPServerThread");
	    	
	    	this.bindAddr = bindAddr;
	    	
	    	this.udpPort = udpPort;
	    	
	    	this.brdCstMsg = brdCstMsg;
	    	
	    	socket = new MulticastSocket(udpPort);
        }
    
    public UDPServerThread() throws IOException {
    	this("UDPServerThread");
        }

        public UDPServerThread(String name) throws IOException {
            super(name);
            
        }
    
    public void run() {
    	try {
    		for (int i =0; i< 200; i++) {
	            byte[] buf = new byte[256];
	            
	            buf = brdCstMsg.getBytes();
	
	            InetAddress group = InetAddress.getByName(bindAddr);
	            
	            DatagramPacket packet;
	            
	            packet = new DatagramPacket(buf, buf.length, group, udpPort);
	            
	            socket.send(packet);
	            
	            try {
	                sleep((long)Math.random() * FIVE_SECONDS);
	            } 
	            catch (InterruptedException e) { }
    		}
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        socket.disconnect();
        socket.close();
        
    }
}